#!/bin/bash

if [ "$1" == "--help" ] || [ $# -lt 2 ]; then
	echo -e "Uso: run.sh puerto caso [valgrind]\n"
	exit -1
fi

puerto=$1
caso=$2
cant_lientes=500
server="server"
client="client"

if [ "$3" == "valgrind" ]; then
	pre_server='valgrind --gen-suppressions=all --tool=memcheck --trace-children=yes --track-fds=yes --time-stamp=yes --num-callers=20 --error-exitcode=42 --db-attach=no --leak-check=full --leak-resolution=med --log-file=valgrind_server.out '
	pre_client='valgrind --gen-suppressions=all --tool=memcheck --trace-children=yes --track-fds=yes --time-stamp=yes --num-callers=20 --error-exitcode=42 --db-attach=no --leak-check=full --leak-resolution=med --log-file=valgrind_client$n.out '
fi

echo "Probando caso '$2' en puerto $1"

if [ -f __stderr__ ] || [ -f __stderr__ ]; then
	rm __stderr__ __stdout__ *.out
fi

echo -n "Server..."
mkfifo server-stdin
cp ../cp/$caso/redInicial.txt ./red.txt
cp ../cp/$caso/CVEInfo.txt ./cve.txt
$pre_server ./$server $puerto red.txt cve.txt <> server-stdin > __stdout__ 2> __stderr__ &
sleep 1
ps $! > /dev/null
server_status=$? 
if [ $! -gt 0 ] && [ $server_status -eq 0 ]; then
	echo -e "OK\nServer PID $!"
	server_pid=$!
else
	echo "Error"
	rm server-stdin
	exit 2
fi


for (( n=0; n < $cant_lientes; n++ )); do
  if [ -f "../cp/$caso/client$n.in" ]; then
		echo "Cliente $n"
		eval $pre_client ./$client 127.0.0.1:$puerto < ../cp/$caso/client$n.in > client$n.out
	fi
done

for (( n=0; n < $cant_lientes; n++ )); do
  if [ -f "../cp/$caso/client$n.in" ]; then
    echo "Salida de cliente $n"
		diff client$n.out ../cp/$caso/client$n.out
		if [ $? -eq 0 ]; then
			echo "OK"
		else
			echo "Error"
		fi
  fi
done


echo -n "Terminando server..."
echo -e "q\n" >> server-stdin
rm server-stdin
echo "OK"
sleep 1


echo -n "red final de server..."
diff red.txt ../cp/$caso/redFinal.txt > /dev/null
if [ $? -eq 0 ]; then
	echo "OK"
else
	echo "Error"
fi

